import { createStore } from 'vuex'
import roleService from '@/services/roleService'
import userService from '@/services/userService'

export default createStore({
  state: {
    roles: [],
    users: [],
    user: null,
    subsystems: [],
    tenant: null,
    tabs: [],
    loading: false,
  },
  mutations: {
    setLoading(state, status) {
      state.loading = status;
    },
    setRoles(state, roles) {
      state.roles = roles
    },
    setUsers(state, users) {
      state.users = users
    },
    setUser(state, user) {
      state.user = user;
    },
    setSubsystems(state, subsystems) {
      state.subsystems = subsystems;
    },
    setTenant(state, tenant) {
      state.tenant = tenant;
    },
    addTab(state, tab) {
      if (!state.tabs.some(existingTab => existingTab.id === tab.id)) {
        state.tabs.push(tab);
      }
    },
    removeTab(state, index) {
      state.tabs.splice(index, 1);
    },
  },
  actions: {
    fetchRoles({ commit }) {
      roleService.getRoles().then(response => {
        commit('setRoles', response.data)
      })
    },
    fetchUsers({ commit }) {
      userService.getUsers().then(response => {
        commit('setUsers', response.data)
      })
    },
    login({ commit }, user) {
      // 模拟登录过程
      localStorage.setItem('token', 'your-token');
      commit('setUser', user);
    },
    logout({ commit }) {
      localStorage.removeItem('token');
      commit('setUser', null);
    },
    fetchSubsystems({ commit }) {
      // 模拟获取子系统
      const subsystems = [/* 子系统数据 */];
      commit('setSubsystems', subsystems);
    },
    fetchTenant({ commit }) {
      // 模拟获取租户信息
      const tenant = {/* 租户信息 */};
      commit('setTenant', tenant);
    },
  },
  modules: {}
})